<script setup lang="ts">
import { useTableData, type MeasuringTool } from './composable'
import type { CustomDialogInstance } from '@/types'
import { bindMeteringDevice } from '@/api/modules/gateway'
import { Close } from '@element-plus/icons-vue'

defineOptions({ name: 'MaintainAssociationModal' })
const props = defineProps<{
  pid?: string | number
}>()
const emits = defineEmits<{
  (e: 'refreshOnClosed'): void
}>()
const dialogRef = ref<CustomDialogInstance>()
const tableListsRef = ref<any>()
const { theme } = storeToRefs(useDesignStore())

// 弹框beforeClose的标识 点击保存关闭时不执行该回调
const flag = ref(true)

const type = ref<0 | 1>(1)
const pointId = ref()
const keyword = ref('')
const { loading, columns, tableData, pagination, getLists, del } = useTableData()

// 按页码缓存选中的数据
const selections = shallowRef<MeasuringTool[]>([])

const selectionsCount = computed(() => {
  return unref(selections).length
})
async function clickSave(done: () => void) {
  if (selectionsCount.value === 0) {
    done()
    flag.value = false
    // close()
    ElMessage.warning('请选择计量器具')
    return
  }

  const toolsIdList = unref(selections).map(v => v.id)
  const params = {
    gatewayId: props.pid,
    toolsIdList,
  }
  // console.log(toolsIdList)
  try {
    await bindMeteringDevice(params)
    ElMessage.success('保存成功')
    done()
    flag.value = false
    close()
    // emits('refreshOnClosed')
  }
  catch (e) {
    done()
  }
}
async function clickSearch() {
  pagination.pageNumber = 1
  await nextTick()
  getTableData()
}

function getTableData() {
  const params = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    keyword: keyword.value,
    pointId: pointId.value,
    type: type.value,
    pid: props.pid,
  }
  getLists(type.value, params)
}

async function clickRowRemove(row: MeasuringTool) {
  if (row.id) {
    const res = await del(row.id)
    res && getTableData()
  }
}

function updateSelections() {
  const tt = unref(tableData)
  const mm = unref(selections)
  const ss = tableListsRef.value?.tableOnMethod('getSelectionRows')
  const isChecked = (row: MeasuringTool) => {
    return ss.some((v: MeasuringTool) => v.id === row.id)
  }
  const has = (row: MeasuringTool) => {
    return mm.some(v => v.id === row.id)
  }

  // 更新当前页选中的数据缓存
  for (const item of tt) {
    if (isChecked(item)) {
      if (!has(item)) {
        mm.push(item)
      }
    }
    else {
      if (has(item)) {
        mm.splice(mm.findIndex(v => v.id === item.id), 1)
      }
    }
  }

  selections.value = mm
  triggerRef(selections)
}

function reset(t: 0 | 1 = 1, cacheSelections = false) {
  flag.value = true
  type.value = t
  keyword.value = ''
  if (!cacheSelections) {
    selections.value = []
    triggerRef(selections)
  }
  pointId.value = undefined

  clickSearch()
}

function open() {
  reset()
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

function beforeClose(handler: () => void) {
  if (selectionsCount.value > 0 && flag.value) {
    ElMessageBox.confirm(`是否放弃保存已勾选了的${selectionsCount.value}个计量器具？`, '提示', {
      type: 'warning',
    })
      .then(() => {
        handler()
      })
      .catch(() => {})
  }
  else {
    handler()
  }
}

function removeSelect(o: MeasuringTool) {
  const t = tableListsRef.value?.tableOnMethod('getSelectionRows')
  const s = t.find((i: MeasuringTool) => i.id === o.id)
  if (s) {
    // 取消当前表格中的选中，并更新currentSelected数据
    tableListsRef.value?.tableOnMethod('toggleRowSelection', s, false)
  }

  // 移除数据缓存中所选中
  const ss = selections.value
  for (const item of ss) {
    if (item.id === o.id) {
      ss.splice(ss.indexOf(item), 1)
    }
  }
  selections.value = ss
  triggerRef(selections)
}

watch(() => type.value, (val) => {
  reset(val, true)
})

watch(
  () => tableData.value,
  (val: MeasuringTool[]) => {
    const selectionsCache = selections.value ?? []
    if (!tableListsRef.value || type.value === 1)
      return
    if (selectionsCache.length === 0) {
      // 清除
      tableListsRef.value?.tableOnMethod('clearSelection')
    }
    else {
      val.forEach((item) => {
        const index = selectionsCache.findIndex(i => i.id === item.id)
        if (index !== -1) {
          tableListsRef.value?.tableOnMethod('toggleRowSelection', item, true)
        }
      })
    }
  },
  {
    flush: 'post',
  },
)

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="维护关联计量器具"
    need-saving :no-max-height="true"
    :show-confirm-button="type === 0"
    :cancel-button-text="type === 0 ? '取消' : '关闭'"
    :before-close="beforeClose"
    @closed="emits('refreshOnClosed')"
    @confirm="clickSave"
  >
    <TableLists
      ref="tableListsRef"
      :lists="tableData"
      :columns="type === 0 ? columns : columns.slice(1)"
      :loading="loading"
      :height="type === 0 ? 240 : 340"
      :operate-width="90"
      :style="
        theme === 'dark' ? null : '--el-table-header-bg-color: var(--el-bg-color-page);'
      "
      @select="updateSelections"
      @select-all="updateSelections"
    >
      <template #actions>
        <div class="w-full flex items-center !mb-3">
          <ElRadioGroup v-model="type">
            <ElRadio :value="1">
              已选
            </ElRadio>
            <ElRadio :value="0">
              未选
            </ElRadio>
          </ElRadioGroup>
          <span class="ml-auto">用能单元：</span>
          <PointTreePicker v-model="pointId" />
          <span class="ml-4">模糊查询：</span>
          <ElInput v-model="keyword" class="w-200px" placeholder="编号/名称" clearable />
          <SearchButton class="ml-3" @click="clickSearch" />
        </div>
      </template>
      <template v-if="type === 1" #operate="{ row }">
        <ElButton type="danger" text bg @click="clickRowRemove(row)">
          移除
        </ElButton>
      </template>
    </TableLists>
    <div class="mt-3 flex justify-end">
      <ElPagination
        v-model:current-page="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        @change="getTableData"
      />
    </div>
    <div v-if="type === 0">
      <h2 class="fs-16 font-normal">
        已勾选 <span style="color: var(--el-color-primary);">{{ selectionsCount }}</span> 个
      </h2>
      <div class="h-150px overflow-auto">
        <div class="flex flex-wrap gap-2">
          <div v-for="child in selections" :key="child.id" class="inline-flex items-center border rounded-sm px-2 py-1 line-height-relaxed">
            <code class="text-gray">[{{ child.measuringToolNumber }}]：</code>
            <span class="flex-1">{{ child.measuringToolName }}</span>
            <ElIcon class="ml-2 cursor-pointer" @click="removeSelect(child)">
              <Close />
            </ElIcon>
          </div>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>
